package linkedlist;

/**
 * @author : Rookie
 * @description : 翻转单链表
 * @date : 2023/8/19
 */
public class ReverseSingleList {

    public static void main(String[] args) {
        int[] elements = new int[] {1,2,3,4,5};
        Node head = new Node(elements[0]);
        Node curr = head;
        for (int i = 1; i < elements.length; i++) {
            curr.next = new Node(elements[i]);
            curr = curr.next;
        }
        System.out.println("旧的链表如下：");
        print(head);
        Node newHead = reverseByRecursion(null,head);
        System.out.println("=====================");
        System.out.println("翻转之后的链表：");
        print(newHead);
    }

    private static Node reverseByCycle(Node head) {
        Node curr = head;
        Node prev = null;
        Node temp = null;
        while (curr != null) {
            // 暂存当前节点的下一节点
            temp = curr.next;
            // 赋值下一节点为上一节点
            curr.next = prev;
            // 上一节点向下遍历
            prev = curr;
            // 当前节点向下遍历
            curr = temp;
        }
        return prev;
    }

    private static Node reverseByRecursion(Node prev,Node curr) {
        if (curr == null) {
            return prev;
        }
        Node temp = curr.next;
        curr.next = prev;
        prev = curr;
        curr = temp;
        return reverseByRecursion(prev,curr);
    }

    private static void print(Node head) {
        Node curr = head;
        while (curr != null) {
            System.out.print(curr.value + " ");
            curr = curr.next;
        }
    }

    static class Node {
        private int value;
        private Node next;

        public Node(int value) {
            this.value = value;
        }
    }
}
